#!/usr/bin/perl -s

use strict;
use warnings;

use EBox;
use EBox::Gettext;
use EBox::Global;
use Error qw(:try);

if (scalar @ARGV == 1) {
    my $chroot = $ARGV[0];
    if ( -f "/opt/ltsp/images/$chroot.img" ) {
        EBox::init();

        my $ltsp = EBox::Global->modInstance('ltsp');

        $ltsp->st_set_string('work', 'update');
        $ltsp->st_set_string('error', '');

        print "Updating $chroot image...\n";

        my $CHROOT_DIR = "/opt/ltsp/$chroot";
        my $cmd = "chroot $CHROOT_DIR mount -t proc none /proc "
                  . "&& chroot $CHROOT_DIR apt-get update "
                  . "&& chroot $CHROOT_DIR env LTSP_HANDLE_DAEMONS=false apt-get dist-upgrade -y "
                  . "&& umount /opt/ltsp/$chroot/proc "
                  . "&& ltsp-update-kernels "
                  . "&& ltsp-update-image --arch $chroot";

        try {
            # TODO: add more messages to ltsp.log (with timestamps)
            EBox::Sudo::root("$cmd >> /var/log/zentyal/ltsp.log");
        } otherwise {
            $ltsp->st_set_string('error', __('Update image failed'));
            print "Update image failed. Check /var/log/zentyal/ltsp.log for details.\n";
            # In case the command failed before the umount
            EBox::Sudo::root("umount /opt/ltsp/$chroot/proc > /dev/null");
        } finally {
            $ltsp->st_set_string('work', 'none');
        };
    } else {
        print "/opt/ltsp/images/$chroot.img does not exist.\n";
    }
} else {
    print "Usage: update-image chroot\n";
}
